package com.cmsz.uregs.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.cmsz.uregs.dao.UserDao;
import com.cmsz.uregs.entity.User;

@Repository
public class UerDaoImpl implements UserDao {

	@PersistenceContext
	private EntityManager em;

	public User addUser(User user) {
		em.persist(user);
		return user;
	}

	public List<User> findAllUsers() {
		String jpql = "from User";
		return em.createQuery(jpql, User.class).getResultList();
	}

	@Override
	public void deleteUser(int id) {
		User user = em.find(User.class, id);
		em.remove(user);
	}

	@Override
	public User findUserByName(String username) {
		String jpql = "from User u where u.username=:username";
		List<User> users = em.createQuery(jpql, User.class)
				.setParameter("username", username).getResultList();
		return users.size() > 0 ? users.get(0) : null;
	}
	
	public User findUser(int id){
		return  em.find(User.class, id);
	}
	
	public void updateUser(User user){
		User userManaged=em.find(User.class, user.getId());
		userManaged.setName(user.getName());
		userManaged.setPassword(user.getPassword());
		userManaged.setAge(user.getAge());
		userManaged.setEmail(user.getEmail());
		userManaged.setNic(user.getNic());
		userManaged.setPhone(user.getPhone());
		userManaged.setSelfshow(user.getSelfshow());
		userManaged.setSex(user.getSex());
		em.persist(userManaged);
	}
}
